package com.youtui.common.util;

import java.security.Key;
import java.util.Date;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Component
public class JwtTokenUtil {

	@Value("${api.secret:youtui}")
	String apiSecret;

	/**
	 * 获取jwt secret api.secret 使用constant 配置 秘钥
	 * 
	 * @return
	 */
	private Key getKeyInstance() {
		// return MacProvider.generateKey(); //随机返回一个默认值
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiSecret);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		return signingKey;
	}

	/**
	 * 创建jwt token
	 * 不推荐使用
	 * @param claims
	 * @param subject
	 * @return
	 */
	public String createJwtToken(Map<String, Object> claims, String subject) {
		return Jwts.builder().setClaims(claims).setIssuedAt(new Date()).setSubject(subject)
				.signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
	}

	/**
	 * 创建带有过期时间的 jwt token 
	 * @param claims 个人信息map
	 * @param subject 主题
	 * @param expMillis 过期时间 毫秒
	 * @return
	 */
	public String createJwtToken(Map<String, Object> claims, String subject, Long expMillis) {

		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		JwtBuilder builder = Jwts.builder().setClaims(claims).setIssuedAt(now).setSubject(subject)
				.signWith(SignatureAlgorithm.HS256, getKeyInstance());
		if (expMillis > 0) {
			Long exp = nowMillis + expMillis;
			builder.setExpiration(new Date(exp)).setNotBefore(now);
		}

		return builder.compact();
	}

	/**
	 * 校验jwt token信息是否合法
	 */
	public Map<String, Object> verifyJwtToken(String token) {
		try {
			Map<String, Object> jwtClaims = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token)
					.getBody();
			return jwtClaims;
		} catch (Exception e) {
			return null;
		}
	}

}